package com.baidu.interceptor;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;








import com.baidu.controller.UserController;
import com.baidu.emus.ErrorCode;
import com.baidu.model.SysUser;
import com.baidu.util.CommonUtil;
import com.baidu.util.MD5Util;
import com.baidu.vo.SysUserInfo;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.oreilly.servlet.Base64Decoder;

public class LoginInterceptor implements Interceptor {
	@Override
	public void intercept(Invocation ai) {
		Controller c = ai.getController();
		//获取cookie，取得sessionId
		String cookieValue = c.getCookie("LOGINBUSS");
		if(StrKit.isBlank(cookieValue)){
			c.redirect(CommonUtil.getHostPath(c.getRequest())+"user/toLogin");
			return;
		}
		try {
			cookieValue = URLDecoder.decode(cookieValue, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		String cookieValueAfterDecode = "";
		try {
			cookieValueAfterDecode = new String(Base64Decoder.decode(cookieValue).getBytes(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			c.setAttr("status", ErrorCode.loginFailed.getCode());
			c.setAttr("message", "非法登陆");
			c.redirect(CommonUtil.getHostPath(c.getRequest())+"user/toLogin");
			return;
		}
		String[] cookieValues = cookieValueAfterDecode.split(":");
		if(cookieValues.length != 3){
			c.setAttr("status", ErrorCode.loginFailed.getCode());
			c.setAttr("message", "非法登陆");
			c.redirect(CommonUtil.getHostPath(c.getRequest())+"user/toLogin");
			return;
		}
		long validTimeInCookie = new Long(cookieValues[1]);
		if(validTimeInCookie < System.currentTimeMillis()){//cookie失效
			c.redirect(CommonUtil.getHostPath(c.getRequest())+"user/toLogin");
			return;
		}
		String userName = cookieValues[0];
		SysUser user = SysUser.dao.findByName(userName);
		//取出用户名密码 加密验证
		if(user != null){
			String md5ValueInCookie = cookieValues[2];
			String md5ValueFromUser =MD5Util.toMd5(user.getStr("userName") + ":" + user.getStr("password") + ":" + validTimeInCookie + ":" + UserController.secretKey);
			//将结果与Cookie中的MD5码相比较,如果相同,写入Session,自动登陆成功,并继续用户请求
			if(md5ValueFromUser.equals(md5ValueInCookie)){
			       c.setSessionAttr("user", new SysUserInfo(user.getStr("guid"),user.getStr("userName"),user.getStr("nickName"),user.getInt("group")));
			       c.setAttr("user", user);
			       ai.invoke();
			}
		}else{
			c.redirect(CommonUtil.getHostPath(c.getRequest())+"user/toLogin");
			return;
		}
	}
}
